$(function(){
	var dropbox = $('#dropbox'),
		message = $('.message', dropbox);
	dropbox.filedrop({
		// The name of the $_FILES entry:
		paramname:'pic',
		maxfiles: 1,
                maxfilesize: 0.5,
		url: 'post_file.php',	
		uploadFinished:function(i, file, response){
			$.data(file).addClass('done');
			// response is the JSON object that post_file.php returns
                        var url = response['status'].split(":");
                        if(url[0] === "Url"){
                            document.getElementById('photo_url').value = url[1];
                            var pl = new SOAPClientParameters();
                            pl.add("url", url[1]);
                            SOAPClient.invoke("/m/", "getColorBar", pl, true, callback_getColorBar);
                            doWidthChangeMem(document.getElementById('dropbox-form'), 970, 365, 10, 10, 0.5);
                            document.getElementById('upload_photo').style.display = 'inherit';
                        }
		},
                error: function(err, file) {
			switch(err) {
				case 'BrowserNotSupported':
					showMessage('Your browser does not support HTML5 file uploads!');
					break;
				case 'TooManyFiles':
					alert('Too many files! Please select 1 at most!');
					break;
				case 'FileTooLarge':
					alert(file.name+' is too large! Please upload files up to 512kb.');
					break;
				default:
					break;
			}
		},
		// Called before each upload is started
		beforeEach: function(file){
			if(!file.type.match(/^image\//)){
				alert('Only images are allowed!');
				
				// Returning false will cause the
				// file to be rejected
				return false;
			}
                        $("#dropbox").html('<span class="message" id="message" style="display: none;">Drop images here to upload. <br><i>(they will only be visible to you)</i></span>');
                        document.getElementById("photo_title").value = "";
                        document.getElementById("photo_description").value = "";
		},
		uploadStarted:function(i, file, len){
			createImage(file);
		},
		
		progressUpdated: function(i, file, progress) {
			$.data(file).find('.progress').width(progress);
		}
    	 
	});
	
        function callback_getColorBar(r){
            $('ul#color-chips').html(r);
            var colors = '';
            $('ul#color-chips a').each(function(d) {
                colors += $(this).attr('title') + ';';
            });
            $('#photo_allcolor').val(colors);
        }
        
        function doWidthChangeMem(elem,startWidth,endWidth,steps,intervals,powr) { 
        //Width changer with Memory by www.hesido.com
            if (elem.widthChangeMemInt)
                window.clearInterval(elem.widthChangeMemInt);
            var actStep = 0;
            elem.widthChangeMemInt = window.setInterval(
                function() { 
                  elem.currentWidth = easeInOut(startWidth, endWidth, steps, actStep, powr);
                  elem.style.width = elem.currentWidth + "px"; 
                  actStep++;
                  if (actStep > steps) window.clearInterval(elem.widthChangeMemInt);
                } 
                ,intervals);
        }
        
        function easeInOut(minValue,maxValue,totalSteps,actualStep,powr) { 
        //Generic Animation Step Value Generator By www.hesido.com 
            var delta = maxValue - minValue; 
            var stepp = minValue+(Math.pow(((1 / totalSteps) * actualStep), powr) * delta); 
            return Math.ceil(stepp);
        } 

	var template = '<div class="preview" id="preview">'+
                            '<span class="imageHolder">'+
                                    '<img />'+
                                    '<span class="uploaded"></span>'+
                            '</span>'+
                            '<div class="progressHolder">'+
                                    '<div class="progress"></div>'+
                            '</div>'+
                        '</div>'; 
	
	
	function createImage(file){

		var preview = $(template), 
			image = $('img', preview);
			
		var reader = new FileReader();
		
		image.width = 100;
		image.height = 100;
		
		reader.onload = function(e){
			
			// e.target.result holds the DataURL which
			// can be used as a source of the image:
			
			image.attr('src',e.target.result);
		};
		
		// Reading the file as a DataURL. When finished,
		// this will trigger the onload function above:
		reader.readAsDataURL(file);
		
		message.hide();
		preview.appendTo(dropbox);
		
		// Associating a preview container
		// with the file, using jQuery's $.data():
		
		$.data(file,preview);
	}

	function showMessage(msg){
		message.html(msg);
	}

});